#include "const.h"

enum {
	TOKEN_EOF = 0,
	TOKEN_COLON = ':',

	__TOKEN_START=256,
	TOKEN_IDENT
};

static char gLexan[512] = { 0, };
static char gCur = 0, gLook = 0;

static char int__process(buffer_t b) {
	char c;

	if (!b_look(b))
		return 0;

	c = b_read(b);
	if (c=='\r' && b_look(b)=='\n')
		c = b_read(b);
	else if(c=='\r')
		c = '\n';

	return c;
}
static char int__read(buffer_t b) {
	gCur = gLook;
	gLook = int__process(b);

	return gCur;
}

static int int__lex(buffer_t b) {
	size_t i;

	gLexan[i = 0] = 0;

	if (!gCur) {
		do {
			if (!int__read(b))
				return TOKEN_EOF;
		} while(gCur <= ' ');
	}

	if (gCur==':') {
		gLexan[0] = ':';
		gLexan[1] = 0;

		gCur = 0; //force gCur to be retrieved again, else infinite loop

		return TOKEN_COLON;
	}

	while(1) {
		if (gCur=='\\') {
			if (gLook=='\n') {
				do {
					if (!int__read(b))
						break;

				} while(gCur <= ' ');

				continue;
			}

			if (gLook==' ') {
				gLexan[i++] = int__read(b);
				continue;
			}

			gCur = '/'; //correct path reads
		} else if(gCur==':') {
			if (gLook<=' ') {
				gLexan[i] = 0;
				return TOKEN_IDENT; //leave gCur for the next call
			}
		} else if(gCur<=' ') {
			gLexan[i] = 0;
			gCur = 0; //force read on next call

			return TOKEN_IDENT;
		}

		gLexan[i++] = gCur;
		int__read(b);
	}
}

////////////////////////////////////////////////////////////////////////////////

void readdeps(const char *filename) {
	buffer_t b;
	var_t v;
	char tmp[256];
	int tok;

	if (!(b = b_open(filename)))
		return;

	gLook = 0;
	int__read(b);

	v = (var_t)0;
	tmp[0] = 0;

	do {
		tok = int__lex(b);

		if (tok==TOKEN_COLON) {
			char arrname[512], arrptr[512];

			if (tmp[0]) {
				snprintf(arrname, sizeof(arrname)-1, "__dep__.%s", tmp);
				arrname[sizeof(arrname)-1] = 0;

				snprintf(arrptr, sizeof(arrptr)-1, "__ptr__.%s", tmp);
				arrname[sizeof(arrptr)-1] = 0;

				v = v_new_array(arrname, arrptr, 8);

				//fprintf(stderr, "DEBUG: start \"%s\"\n", tmp);
				//fflush(stderr);
			}

			tmp[0] = 0;
			continue;
		}

		if (v && tmp[0]) {
			//fprintf(stderr, "DEBUG: +\"%s\"\n", tmp);
			//fflush(stderr);

			v_array_push(v, tmp);
			tmp[0] = 0;
		}

		if (tok==TOKEN_IDENT)
			i_strcpy(tmp, sizeof(tmp), gLexan);
	} while(tok != TOKEN_EOF);

	//fprintf(stderr, "DEBUG: done\n");
	//fflush(stderr);

	b_close(b);
}
